package com.lincoln.authapp.service;

import com.lincoln.entity.user.DbUser;
import com.lincoln.entity.user.OauthUser;
import com.lincoln.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

/**
 * @author Lincoln
 */
@Service(value = "userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    /**
     * 传入String类型id查询DbUser
     *
     * @param input
     * @return
     */
    @Override
    public UserDetails loadUserByUsername(String input) {
        DbUser user = null;
        try {
            long id = Long.parseLong(input);
            user = userService.findById(id);
        } catch (NumberFormatException e) {
            user = userService.findByUserName(input);
        } catch (Exception e) {
            throw e;
        }
        if (user == null)
            throw new BadCredentialsException("Bad credentials");
        OauthUser oauthUser = new OauthUser(user);
        new AccountStatusUserDetailsChecker().check(oauthUser);

        return oauthUser;
    }

}
